package com.ruoyi.framework.config.dynamic;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author anan.
 * @version 1.0
 * @create 2021-06-13 17-03
 */
@Configuration
public class DynamicDataSourceConfig {

	@Bean
	public DynamicDataSourceProvider dynamicDataSourceProvider() {
		// TODO 数据源
		return new AbstractJdbcDataSourceProvider(
			"oracle.jdbc.driver.OracleDriver",
			"jdbc:oracle:thin:@10.10.1.40:1521/gmqruoyi",
			"anan",
			"mfkdgefhn123") {
			@Override
			protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
				Map map = new HashMap(16);
				ResultSet rs = statement.executeQuery("select * from data_sources");
				while (rs.next()) {
					String name = rs.getString("name");
					String username = rs.getString("username");
					String password = rs.getString("password");
					String url = rs.getString("url");
					String driver = rs.getString("driver");
					DataSourceProperty property = new DataSourceProperty();
					property.setUsername(username);
					property.setPassword(password);
					property.setUrl(url);
					property.setDriverClassName(driver);
					map.put(name, property);
				}
				return map;
			}
		};
	}
}
